package com.wuliupai.delivery.wuliupaidelivery.activity;

import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.wuliupai.delivery.wuliupaidelivery.R;
import com.wuliupai.delivery.wuliupaidelivery.constants.CommConstants;
import com.wuliupai.delivery.wuliupaidelivery.constants.Flag;
import com.wuliupai.delivery.wuliupaidelivery.db.City;
import com.wuliupai.delivery.wuliupaidelivery.db.CityAdapter;
import com.wuliupai.delivery.wuliupaidelivery.db.CityHistoryBean;
import com.wuliupai.delivery.wuliupaidelivery.db.DBHelper;
import com.wuliupai.delivery.wuliupaidelivery.db.DBUtil;
import com.wuliupai.delivery.wuliupaidelivery.db.QuickIndexBar;
import com.wuliupai.delivery.wuliupaidelivery.db.ReadAssets;
import com.wuliupai.delivery.wuliupaidelivery.utils.LogUtils;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import ca.barrenechea.widget.recyclerview.decoration.StickyHeaderDecoration;


/**
 * Descriptions：地址选择界面
 * <p>
 * Author：ChenME
 * Date：11/21/2016
 * Email：ibelieve1210@163.com
 */
@EActivity(R.layout.act_select_place)
public class PlaceSelectActivityStep2 extends AppBaseActivity {

    @Bean(DBUtil.class)
    DBUtil dbUtil;

    @ViewById(R.id.recyclerView)
    RecyclerView recyclerView;
    @ViewById(R.id.tv_province)
    TextView tv_province;//省份
    @ViewById(R.id.tv_city)
    TextView tv_city;//城市
    @ViewById(R.id.tv_area)
    TextView tv_area;//区县

    @ViewById(R.id.tv_touchTips)
    TextView tv_touchTips;

    @ViewById(R.id.qib)
    QuickIndexBar QIBar;

    public static final int Result_SelectPlace = 0x123f;

    private List<City> cityList = new ArrayList<>();//城市列表
    private int flag = 0;
    //    private HashMap<String, Integer> letters = new HashMap<>();
    private String[] resultProvince = new String[2];
    private String[] resultCity = new String[2];
    private String[] resultArea = new String[2];

    private ReadAssets readAssets;
    private SQLiteDatabase db;

    private LinearLayoutManager manager;

    @Extra("accurate")
    int accurate = CommConstants.ACCURATE_AREA_NO_ALL;//精确，精确到县，默认没有全国、全省和全市
    @Extra("pageTitle")
    String pageTitle = "";
    private CityAdapter adapter;

    /**
     * 开始显示的级别
     * SelectPlace_StartLevel_Area：直接显示县
     */
    @Extra("startLevel")
    int startLevel;
    @Extra("cityCode")
    String cityCode;//城市的Code

    private DBHelper dbHelper;

    @AfterViews
    void startPage() {
        initViews();
        initCitySelector();//初始化城市列表
        dbHelper = new DBHelper(this);

        if (CommConstants.SelectPlace_StartLevel_Area == startLevel) {
            tv_province.setVisibility(View.GONE);
            tv_city.setVisibility(View.GONE);
            tv_area.setVisibility(View.VISIBLE);

            setArea(cityCode);
            setProvinceEmpty();
            setCityEmpty();
            flag = 2;
        } else {
            setProvince();//设置省份
        }
    }

    private void initViews() {
        setDefaultTitle(this, pageTitle);

        //条目间的间隔线

        ca.barrenechea.widget.recyclerview.decoration.DividerDecoration divider = new ca.barrenechea.widget.recyclerview.decoration.DividerDecoration.Builder(this)
                .setHeight(R.dimen.default_divider_height)
                .setPadding(R.dimen.default_divider_padding)
                .setColorResource(R.color.color_defaultDivider)
                .build();

        manager = new LinearLayoutManager(this);

        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(manager);
        recyclerView.addItemDecoration(divider);

        adapter = new CityAdapter(this, cityList);

        //设置悬浮索引
        StickyHeaderDecoration decor = new StickyHeaderDecoration(adapter);

        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(decor, 1);

        //侧拉索引改变监听
        QIBar.setOnLetterChangeListener(new QuickIndexBar.OnLetterChangeListener() {
            @Override
            public void onLetterChange(String letter) {

                tv_touchTips.setVisibility(View.VISIBLE);
                tv_touchTips.setText(letter);

                for (int i = 0; i < cityList.size(); i++) {

                    if (letter.equals(cityList.get(i).firstLetter.charAt(0) + "")) {

                        int position = adapter.getPositionForSection(cityList.get(i).firstLetter.charAt(0));
                        if (position != -1) {
                            //滑动到指定位置
                            manager.scrollToPositionWithOffset(position, 0);
                        }
                        break;
                    }
                }
            }

            @Override
            public void onReset() {
                tv_touchTips.setVisibility(View.GONE);
                tv_touchTips.setText("");
            }
        });

        adapter.setOnItemClickListener(new CityAdapter.OnItemClickListener() {
            @Override
            public void itemClick(View view, int position) {
                City city = cityList.get(position);
                switch (flag) {
                    case 0:
                        if ((CommConstants.ACCURATE_AREA_HAVE_ALL == accurate ||
                                CommConstants.ACCURATE_CITY_HAVE_ALL == accurate) &&
                                0 == position) {
                            //选择了全国
                            setProvinceEmpty();
                            setCityEmpty();
                            setAreaEmpty();
                            setResultAndFinishPage();
                            return;
                        }
                        resultProvince[0] = city.getCode();
                        resultProvince[1] = city.getCityName();
                        setCity(resultProvince[0]);
                        tv_province.setText(resultProvince[1] + "  >");
                        tv_province.setTextColor(getResources().getColor(R.color.color_btnText));
                        tv_city.setVisibility(View.VISIBLE);
                        flag = 1;
                        break;

                    case 1:
                        if ((CommConstants.ACCURATE_AREA_HAVE_ALL == accurate ||
                                CommConstants.ACCURATE_CITY_HAVE_ALL == accurate) &&
                                0 == position) {
                            //选择了全省
                            setCityEmpty();
                            setAreaEmpty();
                            setResultAndFinishPage();
                            return;
                        }
                        resultCity[0] = city.getCode();
                        resultCity[1] = city.getCityName();
                        if (CommConstants.ACCURATE_CITY_NO_ALL == accurate ||
                                CommConstants.ACCURATE_CITY_HAVE_ALL == accurate) {
                            //精确到市，没有全国全省
                            //精确到市，有全国全省
                            setAreaEmpty();
                            setResultAndFinishPage();
                            return;
                        }
                        setArea(resultCity[0]);
                        tv_city.setText(resultCity[1] + "  >");
                        tv_city.setTextColor(getResources().getColor(R.color.color_btnText));
                        tv_area.setVisibility(View.VISIBLE);
                        flag = 2;
                        break;

                    case 2:
                        resultArea[0] = city.getCode();
                        resultArea[1] = city.getCityName();
                        if (CommConstants.ACCURATE_AREA_HAVE_ALL == accurate && 0 == position) {
                            //选择了全市
                            setAreaEmpty();
                        }
                        setResultAndFinishPage();
                        break;
                }
            }
        });
    }

    /**
     * 初始化城市列表
     */
    private void initCitySelector() {
        readAssets = new ReadAssets();

    }

    /**
     * 设置省份
     */
    private void setProvince() {
        db = readAssets.openDatabase(this);
        List<City> cityListTemp = dbUtil.findAllProvince(db);
        if (CommConstants.ACCURATE_AREA_HAVE_ALL == accurate //精确到县，有全国全省全市
                || CommConstants.ACCURATE_CITY_HAVE_ALL == accurate) { //精确到市，有全国全省
            cityList.add(0, new City("", "0", getString(R.string.string_selectPlace_allCountry), "#"));
        }
        Collections.sort(cityList);
        cityList.clear();
        cityList.addAll(cityListTemp);
        adapter.notifyDataSetChanged();
    }

    private void setCity(String cityCode) {
        db = readAssets.openDatabase(this);
        List<City> cityListTemp = dbUtil.findAllCity(db, cityCode);
        if (CommConstants.ACCURATE_AREA_HAVE_ALL == accurate //精确到县，有全国全省全市
                || CommConstants.ACCURATE_CITY_HAVE_ALL == accurate) {//精确到市，有全国全省
            cityList.add(0, new City(resultProvince[0], "0", getString(R.string.string_selectPlace_allProvince), "#"));
        }
        Collections.sort(cityList);
        cityList.clear();
        cityList.addAll(cityListTemp);
        adapter.notifyDataSetChanged();
    }

    private void setArea(String areaCode) {
        db = readAssets.openDatabase(this);
        List<City> cityListTemp = dbUtil.findAllArea(db, areaCode);
        if (CommConstants.ACCURATE_AREA_HAVE_ALL == accurate) {//精确到县，有全国全省全市
            cityList.add(0, new City(resultCity[0], "0", getString(R.string.string_selectPlace_allCity), "#"));
        }
        Collections.sort(cityList);
        cityList.clear();
        cityList.addAll(cityListTemp);
        adapter.notifyDataSetChanged();
    }

    /**
     * 设置选择结果并关闭页面
     */
    private void setResultAndFinishPage() {
        dbHelper.insertCityHistory(new CityHistoryBean(resultArea[0], resultCity[0], resultProvince[0],
                resultArea[1], resultCity[1], resultProvince[1]));
        Intent intent = new Intent();
        intent.putExtra("province", resultProvince);
        intent.putExtra("city", resultCity);
        intent.putExtra("area", resultArea);
        setResult(Result_SelectPlace, intent);
        onBackPressed();
    }

    /**
     * 重新选择城市列表
     */
    @Click(R.id.tv_city)
    void reSelectCity() {
        resetSelectCityViews();
        setCity(resultProvince[0]);
    }

    /**
     * 重新选择
     */
    private void resetSelectCityViews() {
        tv_city.setTextColor(getResources().getColor(R.color.color_defaultTextLight));
        tv_city.setText(getString(R.string.string_selectPlace_toSelectCity));
        tv_area.setVisibility(View.GONE);
        flag = 1;
    }

    /**
     * 重新选择省
     */
    @Click(R.id.tv_province)
    void reSelectProvince() {
        resetSelectCityViews();
        tv_province.setTextColor(getResources().getColor(R.color.color_defaultTextLight));
        tv_province.setText(getString(R.string.string_selectPlace_toSelectProvince));
        tv_city.setVisibility(View.GONE);
        flag = 0;
        setProvince();
    }

    /**
     * 设置县的数据为空
     */
    private void setAreaEmpty() {
        resultArea[0] = "0";
        resultArea[1] = "0";
    }

    /**
     * 设置市的数据为空
     */
    private void setCityEmpty() {
        resultCity[0] = "0";
        resultCity[1] = "0";
    }

    /**
     * 设置省的数据为空
     */
    private void setProvinceEmpty() {
        resultProvince[0] = "0";
        resultProvince[1] = "0";
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        animUtils.popOutAnimation(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}